package com.jason.system.common.util;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.word.WordExportUtil;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletResponse;
import javax.swing.filechooser.FileSystemView;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * @author jie
 * @version 1.0
 * success come from self-discipline
 * @date 2021/4/6 14:31
 */
@Component
public class EasyPoiUtil {

  private static Logger logger = LoggerFactory.getLogger(EasyPoiUtil.class);

  /**
   * word模板地址
   */
  @Value(value = "${myProperties.wordTemplate}")
  public void setFileTemplateUrl(String fileTemplateUrl){
    FileTemplateUrl=fileTemplateUrl;
  }

  private static String FileTemplateUrl;

  /**
   *
   *  导出word数据(07版)
   * @param params map数据集合
   * @param goalName 文件名称
   * @return 文件存储地址
   */
  public static String exportWord(Map<String, Object> params, String goalName){
    try {
      XWPFDocument doc = WordExportUtil.exportWord07(FileTemplateUrl, params);
      // 判断文件存放地址是否存在,没有则创建
      FileSystemView fsv = FileSystemView.getFileSystemView();
      File com=fsv.getHomeDirectory();
      //桌面真实路径
      String desktopUrl = com.getPath();
      File saveFile = new File(desktopUrl);
      if (!saveFile.exists()) {
        logger.info("导出word数据时存储文件目录不存在,为您创建文件夹!");
        saveFile.mkdirs();
      }
      goalName=desktopUrl+goalName+".docx";
      FileOutputStream fos = new FileOutputStream(goalName);
      doc.write(fos);
      fos.close();
    }catch (Exception e) {
      e.printStackTrace();
      logger.error("导出word数据异常:"+e);
      return null;
    }
    return goalName;
  }


  /**
   * 默认导出方法
   * @param list
   * @param title
   * @param sheetName
   * @param fileName
   * @param pojoClass
   * @param response
   */
  public static void defaultExport(List<?> list, String title, String sheetName, String fileName, Class<?> pojoClass, HttpServletResponse response){
    Workbook workbook = getWorkbook(new ExportParams(title,sheetName),pojoClass,list);
    if (workbook != null) {
      downLoadExcel(fileName, response, workbook);
    }
  }

  /**
   * 功能描述：Excel导出
   * @date 2018/7/23 15:35
   * @param fileName 文件名称
   * @param response
   * @param workbook Excel对象
   */
  private static void downLoadExcel(String fileName, HttpServletResponse response, Workbook workbook) {
    try {
      response.setCharacterEncoding("UTF-8");
      response.setHeader("content-Type", "application/vnd.ms-excel");
      response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
      OutputStream out = response.getOutputStream();
      workbook.write(out);
      out.close();
    } catch (IOException e) {
      throw new  RuntimeException(e);
    }
  }

  /**
   * @param entity    表格标题属性
   * @param pojoClass Excel对象Class
   * @param dataSet   Excel对象数据List
   */
  private static Workbook getWorkbook(ExportParams entity, Class<?> pojoClass,
                                      Collection<?> dataSet) {
    return ExcelExportUtil.exportExcel(entity, pojoClass, dataSet);
  }
}
